<template>
  <div>
    <div style="padding: 20px;background-color: #fff;">
      <div style="margin-bottom: 20px;display: flex;justify-content: space-between;">
        <div style="display: flex;">
          <!-- <div>开始时间:{{ priceInfo.startTime }}</div> -->

          <JRangeDate :datetime="true" style="width: 400px;height: 50px;" v-model:value="dateRange"
            @change="dateChange" />

          <!-- <div style="margin:  0 50px;">结束时间:{{ priceInfo.endTime }}</div> -->
          <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>未结算金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{
              amountInfo.amountUnsettled }}元
            </div>

          </div>

          <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>已结算金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{
              amountInfo.amountSettled }}元
            </div>

          </div>

          <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>总金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{ amountInfo.amountAll
            }}元
            </div>
          </div>



          <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>商家累计支出金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{ amountInfo.checkTheTotalPaymentAmount
              }}元
            </div>
          </div>
          <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>推广奖励总金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{ tuiAmount
            }}元
            </div>
          </div>
          <!-- <div
            style="width: 200px;font-size: 18px;margin-left: 10px;display: flex;flex-direction: column;align-items: center;">
            <div>累计提现金额</div>
            <div style="margin-top: 10px;font-size: 28px;font-weight: 600;">{{ tuiAmount
              }}元
            </div>
          </div> -->
          <!-- <div style="display: flex;align-items: center;">
            <a-button type="primary" style="margin-right: 100px;" @click="editAmount" v-if="isAmountEdit"> 编辑
            </a-button>
            <a-button type="primary" style="margin-right: 100px;" @click="saveAmount" v-else> 保存 </a-button>
          </div> -->
        </div>


      </div>
      <div style="color: red;">本次最高可结算金额：{{ thisHeignAmount }}元</div>
      <div style="margin-bottom: 20px;font-size: 20px;display: flex;">
        <div style="margin-right: 20px;display: flex;">
          <div style="margin-right: 20px;"> 本次结算金额:</div>
          <div v-if="isAmountEdit">
            {{ benAmount }}元
          </div>
          <a-input type="text" style="font-size: 24px;font-weight: 600;width: 80px;height: 30px;"
            v-model:value="benAmount" v-else />
        </div>
        <div style="display: flex;align-items: center;">
          <a-button type="primary" style="margin-right: 100px;" @click="editAmount" v-if="isAmountEdit"> 编辑 </a-button>
          <a-button type="primary" style="margin-right: 100px;" @click="saveAmount" v-else> 保存 </a-button>
        </div>
      </div>
      <div style="display: flex;justify-content: space-around;">
        <div style="text-align: center;">
          <div>三级权益包 <text style="color: red;">({{ priceInfo.threeCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.three }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.three" v-else />
        </div>
        <div style="text-align: center;">
          <div>二级权益包 <text style="color: red;">({{ priceInfo.towCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.tow }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.tow" v-else />
        </div>
        <div style="text-align: center;">
          <div>一级权益包 <text style="color: red;">({{ priceInfo.oneCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.one }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.one" v-else />
        </div>


        <div style="text-align: center;">
          <div>特级权益包 <text style="color: red;">({{ priceInfo.maxCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.max }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.max" v-else />
        </div>
        <div style="text-align: center;">
          <div>商家补贴权益包<text style="color: red;">({{ priceInfo.merchantSubsidyCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.merchantSubsidy }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.merchantSubsidy" v-else />
        </div>
        <div style="text-align: center;">
          <div>月供权益包<text style="color: red;">({{ priceInfo.monthlyPaymentCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.monthlyPayment }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.monthlyPayment" v-else />
        </div>
        <div style="text-align: center;">
          <div>工资权益包<text style="color: red;">({{ priceInfo.salaryCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.salary }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.salary" v-else />
        </div>
        <div style="text-align: center;">
          <div>募捐权益包<text style="color: red;">({{ priceInfo.fundraisingCount }})</text> </div>
          <div style="margin-top: 10px;font-size: 28px;font-weight: 600;" v-if="isEdit">
            {{
              priceInfo.fundraising }}
          </div>
          <a-input type="text" style="margin-top: 10px;font-size: 28px;font-weight: 600;width: 150px;height: 40px;"
            v-model:value="priceInfo.fundraising" v-else />
        </div>
        <div style="display: flex;align-items: center;">
          <a-button type="primary" style="margin-right: 100px;" @click="editFen" v-if="isEdit"> 编辑 </a-button>
          <a-button type="primary" style="margin-right: 100px;" @click="saveFen" v-else> 保存 </a-button>
        </div>

      </div>

    </div>

    <!--引用表格-->
    <a-popconfirm title="是否确认分红" ok-text="是" cancel-text="否" @confirm="confirm" @cancel="cancel">
      <a-button type="primary" preIcon="ant-design:plus-outlined" style="margin-left: 20px;"> 手动执行分红
      </a-button>
    </a-popconfirm>




    <a-tabs v-model:activeKey="activeKey" @change="change" style="margin: 0 30px;">
      <a-tab-pane key="1" tab="分红详情">
        <a-table :columns="columns1" :data-source="dataSource1" bordered :pagination="pagination"
          @change="handleTableChange">
          <template #bodyCell="{ column, text }">
            <template v-if="column.dataIndex === 'name'">
              <a>{{ text }}</a>
            </template>
          </template>

        </a-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="分红记录" force-render :pagination="pagination" @change="handleTableChange(2)">
        <a-table :columns="columns2" :data-source="dataSource2" bordered>
          <template #bodyCell="{ column, text }">
            <template v-if="column.dataIndex === 'name'">
              <a>{{ text }}</a>
            </template>
          </template>

        </a-table>
      </a-tab-pane>

    </a-tabs>

    <!-- <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" @click="fenMethod" preIcon="ant-design:plus-outlined"> 手动执行分红 </a-button>
        <a-button type="primary" v-auth="'shipMemberDividend:ship_member_dividend:exportXls'"
          preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" v-auth="'shipMemberDividend:ship_member_dividend:importExcel'"
          preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
<a-button v-auth="'shipMemberDividend:ship_member_dividend:deleteBatch'">批量操作
  <Icon icon="mdi:chevron-down"></Icon>
</a-button>
</a-dropdown>

</template>
<template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
<template v-slot:bodyCell="{ column, record, index, text }">
      </template>
</BasicTable> -->
    <!-- 表单区域 -->
    <ShipMemberDividendModal @register="registerModal" @success="handleSuccess"></ShipMemberDividendModal>
  </div>
</template>

<script lang="ts" name="shipMemberDividend-shipMemberDividend" setup>
import { ref, reactive, computed, unref, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import ShipMemberDividendModal from './components/ShipMemberDividendModal.vue'
import { columns, searchFormSchema, superQuerySchema } from './ShipMemberDividend.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, getPrice, distributionOperationManually, addFen, listFen, addAll, getAmountByTime, amountLoglist, queryTheTotalRecommendedIncomeAmount } from './ShipMemberDividend.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import JRangeDate from '/@/components/Form/src/jeecg/components/JRangeDate.vue';
import { useMessage } from '/@/hooks/web/useMessage';
onMounted(() => {
  getList(1)
});
const { createMessage } = useMessage();
const activeKey = ref('1');

const dateRange = ref() // 日期选择范围
const isAmountEdit = ref(true)//金额编辑状态
const benAmount = ref('0')//金额编辑状态

const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();
//注册model
const [registerModal, { openModal }] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '用户分红记录表',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "用户分红记录表",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})
const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext
const priceInfo = reactive({
  amount: 0,
  startTime: '',
  endTime: '',
  fundraising: 0,
  max: 0,
  merchantSubsidy: 0,
  monthlyPayment: 0,
  one: 0,
  salary: 0,
  three: 0,
  tow: 0,
  threeCount: 0,
  fundraisingCount: 0,
  maxCount: 0,
  merchantSubsidyCount: 0,
  monthlyPaymentCount: 0,
  oneCount: 0,
  salaryCount: 0,
  towCount: 0,
})
const pagination = ref(
  {
    current: 1,       // 当前页码
    total: 0,         // 总数据量
  }
)
const thisHeignAmount = ref('')
const tuiAmount = ref('')
const dataSource1 = reactive([])
const dataSource2 = reactive([])
const columns1 = reactive([{
  title: '用户名',
  dataIndex: 'userName',
  key: 'userName',
  align: 'center'
},
{
  title: '手机号',
  dataIndex: 'phone',
  key: 'phone',
  align: 'center'
},
{
  title: '分红说明',
  dataIndex: 'remark',
  key: 'remark',
  align: 'center'
},
{
  title: '金额',
  dataIndex: 'amount',
  key: 'amount',
  align: 'center'
},
{
  title: '时间',
  dataIndex: 'createTime',
  key: 'createTime',
  align: 'center'
},

])
const columns2 = reactive([
  {
    title: '分红说明',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center'
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    align: 'center'
  },
  {
    title: '操作人',
    dataIndex: 'createBy',
    key: 'createBy',
    align: 'center'
  },
  {
    title: '执行时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center'
  },

])
const amountInfo = reactive({
  amountUnsettled: '',
  amountAll: '',
  amountSettled: '',
  checkTheTotalPaymentAmount: ''

})  //金额信息

const listAll = ref()
const getAmount = (startTime, endTime) => {
  getAmountByTime({
    startTime: startTime,
    endTime: endTime
  }).then(res => {
    Object.assign(amountInfo, res)
    benAmount.value = amountInfo.amountUnsettled
    getPriceMethod(amountInfo.amountUnsettled)

  })
}
const getTuiAmount = (startTime, endTime) => {
  queryTheTotalRecommendedIncomeAmount({
    startTime: startTime,
    endTime: endTime
  }).then(res => {
    tuiAmount.value = res;

    // Object.assign(amountInfo, res)
    // benAmount.value = amountInfo.amountUnsettled
    // getPriceMethod(amountInfo.amountUnsettled)

  })
}
getAmount('', '')
getTuiAmount('', '')

// 日期选择器选择
const dateChange = (e) => {
  if (e) {
    getAmount(e.split(',')[0], e.split(',')[1])

  } else {
    getAmount('', '')

  }
}
const fenMethod = () => {

  if (priceInfo.fundraising == 0 && priceInfo.one == 0 && priceInfo.tow == 0 && priceInfo.three == 0 && priceInfo.max == 0 && priceInfo.merchantSubsidy == 0 && priceInfo.monthlyPayment == 0 && priceInfo.salary == 0) {
    createMessage.warning('暂无分红数据');

    return

  }

  distributionOperationManually({
    amount: benAmount.value
  }).then(res => {
    getAmount('', '')
    getList(1)

    // getPriceMethod(amountInfo.amountAll)
    reload();
  })
}
//tab切换
const change = (e) => {
  // pagination.value.current = 1
  if (e == 2) {
    getAmountLoglist(1)


  } else {
    getList(1)
  }

}
const handleTableChange = (e) => {
  pagination.value.current = e.current;
  dataSource1.splice(0, dataSource1.length);
  getList(e.current)

}
const handleTableChange1 = (e) => {
  pagination.value.current = e.current;

  dataSource1.splice(0, dataSource1.length);
  getAmountLoglist(e.current)

}
//获取分红列表
const getList = (pageNo) => {
  list({ userType: 1, pageNo: pageNo }).then(res => {
    Object.assign(dataSource1, res.records)
    pagination.value.total = res.total
  })

}
//获取分红详情
const getAmountLoglist = (pageNo) => {
  amountLoglist({ userType: 1, pageNo: pageNo }).then(res => {
    Object.assign(dataSource2, res.records)
    pagination.value.total = res.total
  })

}

const getPriceMethod = (amountAll) => {


  getPrice({
    amount: amountAll
  }).then(res => {

    Object.assign(priceInfo, res)
    listAll.value = res.returnList;
    thisHeignAmount.value = res.thisHeignAmount

    if (Number(benAmount.value) > Number(thisHeignAmount.value)) {
      benAmount.value = thisHeignAmount.value
    } else {


    }
    res.returnList.forEach(e => {
      if (e.type == 1) {
        priceInfo.one = e.quantity
      } else if (e.type == 2) {
        priceInfo.tow = e.quantity
      } else if (e.type == 3) {
        priceInfo.three = e.quantity
      } else if (e.type == 4) {
        priceInfo.max = e.quantity
      } else if (e.type == 5) {
        priceInfo.merchantSubsidy = e.quantity
      } else if (e.type == 6) {
        priceInfo.monthlyPayment = e.quantity
      } else if (e.type == 7) {
        priceInfo.salary = e.quantity
      } else if (e.type == 8) {
        priceInfo.fundraising = e.quantity
      }
    })
  })
}

// getListFen()
const isEdit = ref(true)
const quantity = ref(0)
const typeInfo = ref(0)

//点击金额编辑
const editAmount = () => {
  isAmountEdit.value = false
}
//点击金额保存

const saveAmount = () => {
  if (Number(benAmount.value) > Number(amountInfo.amountUnsettled)) {
    createMessage.warning('本次结算金额不能超过未结算金额');
    benAmount.value = amountInfo.amountUnsettled
    isAmountEdit.value = true

    return
  }



  isAmountEdit.value = true
  getPriceMethod(benAmount.value)

}

const editFen = () => {
  isEdit.value = false
}
const saveFen = () => {



  if (priceInfo.three > 60) {
    createMessage.warning('三级权益包不能超过60');
    return;
  }
  if (priceInfo.tow > 60) {
    createMessage.warning('二级权益包不能超过60');
    return;
  }
  if (priceInfo.one > 60) {
    createMessage.warning('一级权益包不能超过60');
    return;
  }
  if (priceInfo.max > 75) {
    createMessage.warning('特级权益包不能超过75');
    return;
  }
  if (priceInfo.merchantSubsidy > 30) {
    createMessage.warning('商家补贴权益包不能超过30');
    return;
  }
  if (priceInfo.monthlyPayment > 45) {
    createMessage.warning('月供权益包不能超过45');
    return;
  }
  if (priceInfo.salary > 60) {
    createMessage.warning('工资权益包不能超过60');
    return;
  }
  if (priceInfo.fundraising > 30) {
    createMessage.warning('募捐权益包不能超过30');
    return;
  }
  isEdit.value = true


  listAll.value.forEach(e => {

    if (e.type == 1) {
      e.quantity = priceInfo.one
    } else if (e.type == 2) {
      e.quantity = priceInfo.tow

    } else if (e.type == 3) {
      e.quantity = priceInfo.three

    } else if (e.type == 4) {
      e.quantity = priceInfo.max

    } else if (e.type == 5) {
      e.quantity = priceInfo.merchantSubsidy

    } else if (e.type == 6) {
      e.quantity = priceInfo.monthlyPayment

    } else if (e.type == 7) {
      e.quantity = priceInfo.salary

    } else if (e.type == 8) {
      e.quantity = priceInfo.fundraising
    }
  })

  addAll(listAll.value).then(res => {
    console.log(res);

  })
}


// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);

/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}
/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}

const confirm = (e: MouseEvent) => {
  fenMethod()
};

const cancel = (e: MouseEvent) => {
  console.log(e);

};

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      auth: 'shipMemberDividend:ship_member_dividend:edit'
    }, {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
  ]
}
/**
   * 下拉操作栏
   */
function getDropDownAction(record) {
  return [
    // {
    //   label: '详情',
    //   onClick: handleDetail.bind(null, record),
    // }, {
    //   label: '删除',
    //   popConfirm: {
    //     title: '是否确认删除',
    //     confirm: handleDelete.bind(null, record),
    //     placement: 'topLeft',
    //   },
    //   auth: 'shipMemberDividend:ship_member_dividend:delete'
    // }
  ]
}



</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>